import { request } from '../../request/index'

const app = getApp()

Page({
  data: {
   user: {}
  },
  onShareAppMessage:function(options){},
  onShow: function(e) {
    let user = wx.getStorageSync('user')
    if (!user) {
      wx.navigateTo({url: '../login/login'})
      return
    }
    request({
      url: '/user/' + user.id ,
      method: 'GET'
    }).then(res => {
      this.setData({
        user: res.data
      })
    })
  },
  view() {
    wx.navigateTo({
      url: '../myActivity/index',
    })
  },
  logout() {
    wx.removeStorageSync('user')
    wx.navigateTo({
      url: '../login/login',
    })
  },
  //绑定openid与用户账号
  bind(){

    // 获取openid
    wx.getUserInfo({
      //成功后会返回
      success:(res)=>{
        // console.log(res);
        // 把用户信息存到一个变量中方便下面使用
        let userInfo= res.userInfo
        //获取openId（需要code来换取）这是用户的唯一标识符
        // 获取code值
        wx.login({
          //成功放回
          success:(res)=>{
            // console.log(res);
            let code=res.code
            // 通过code换取openId
            wx.request({
              url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx6c47e36909507d4c&secret=ccd89bca7580181dfede0d3ecb0727cb&js_code=${code}&grant_type=authorization_code`,
              success:(res)=>{
                // console.log(res);
                userInfo.openid=res.data.openid;
                var that=this
                that.setData({
                  openid: res.data.openid
                })
                console.log(this.data.openid)
                console.log(this.data.user)
                this.transmit()
              }
            })

          }
        })

      }
    })

  },

  //后台数据传输
  transmit(){
    //构造请求体
    let data={
      username:this.data.user.username,
      openid:this.data.openid
    }
    console.log(this.data.user.username)
    request({
      url:'/user/useropenid',
      method:'POST',
      data:data
    }).then(res=>{
      if (res.code === '200') {
        // 成功时的操作
        wx.showToast({
          title: '绑定成功',
          icon: 'succcess'
        })
      } else {
        wx.showToast({
          title: '绑定失败',
          icon: 'error'
        })
      }
    })
  }



})


